/**
 * LY.com Inc.
 * Copyright (c) 2004-2018 All Rights Reserved.
 */
package com.gitee.kamismile.gateway.component.route;

import com.gitee.kamismile.gateway.component.config.GatewayConstant;
import jakarta.annotation.PostConstruct;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.event.RefreshRoutesEvent;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;


/**
 * @author dong.li
 * @version $Id: RouteEventHandler, v 0.1 2018/10/18 14:43 dong.li Exp $
 */
@Component
public class RouteEventHandler {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    GatewayConstant gatewayConstant;

    @Autowired
    @Lazy
    RedisRouteDefinitionRepository redisRouteDefinitionRepository;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private ApplicationEventPublisher applicationEventPublisher;

    public void refreshRoutes() {
        redisTemplate.convertAndSend(gatewayConstant.getGatewayRouteNotify(), gatewayConstant.getGatewayRouteNotify());
    }

    @PostConstruct
    public void initSubscriber() {
        this.redisTemplate.execute((connection) -> {
            connection.subscribe((message, bytes) -> {
                logger.info("receive notify msg!");
                redisRouteDefinitionRepository.getRoutes().clear();
                this.applicationEventPublisher.publishEvent(new RefreshRoutesEvent(this));
            }, gatewayConstant.getGatewayRouteNotify().getBytes());
            return null;
        }, true);
    }
}
